import React from 'react';
import reqwest from 'reqwest';
import classnames from 'classnames';
import css from './index.less';
import Layout from 'components/layout';
import { Table, Button, Icon } from 'antd';
import Modal from './components/modal';
import { observer, inject, action } from 'mobx-react';

@inject('store')
@observer
class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false
    };
  }
  showModal() {
    this.setState({
      modalVisible: true
    })
  }

  columns = [{
    title: '消息内容',
    dataIndex: 'm_content',
    key: 'm_content'
  }, {
    title: '时间',
    dataIndex: 'myTime',
    key: 'myTime'
  },{
    title: '操作',
    dataIndex: 'del',
    key: 'del',
    render: (text, record) => (
      <div>
        <Button ghost type="primary" shape="circle" icon="delete" size="small" onClick={this.delMess.bind(this, record)}/>
      </div>
    )
  }];

  delMess(mess) {
    const { store } = this.props;
    store.delMess(mess.m_id)
  }

  addMess(mess) {
    const { store } = this.props;
    store.addMess(mess);
    this.closeModal();
  }

  closeModal() {
    this.setState({
      modalVisible: false
    })
  }

  format (date, fmt) { //author: meizz
    let o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)){
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  }

  componentDidMount() {
  }

  render() {
    const cls = classnames([css.layout]);
    const { store } = this.props;
    const { modalVisible } = this.state;
    const dataSource = [];
    store.messList.forEach((item, index) => {
      item.key = index;
      item.myTime = this.format(new Date(item.m_time), "yyyy-MM-dd hh:mm:ss");
      dataSource.push(item);
    });
    const modalProps = {
      visible: modalVisible,
      addMess: this.addMess.bind(this),
      closeModal: this.closeModal.bind(this)
    };
    return (
      <Layout selected="2" title="消息列表">
        <div className={cls}>
          <div className={css.addBox}>
            <Button type="primary" icon="plus" onClick={this.showModal.bind(this)}>添加消息</Button>
          </div>
          <Table dataSource={dataSource} columns={this.columns} />
        </div>
        <Modal {...modalProps}/>
      </Layout>
    );
  }
}


export default Home;
